<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户模型
 *
 * @author www.dingwei.cn
 */

class AdmUserModel extends MY_Model{
	
	public $tbUser = 'admin';
	private $tbSession = 'admin_session';
    private $tbRole = 'admin_role';
	/**
	 * 获取用户信息通过session
	 * 
	 * @param	string $sessionid	会话id
	 * @return	array
	 */
 	public function getUserInfoBySessionid($sessionid){
 	
 		if( ! $sessionid){
 			return array();
 		}
 		$this->db->select('u.name,u.type,u.county,u.status,u.id,se.ip,r.permissions')
 				 ->join($this->tbUser.' u', 'u.id = se.user_id')
                ->join($this->tbRole.' r', 'r.id = u.role_id', 'left')
                ->where(array('se.sessionid' => $sessionid));
 		$tA = $this->getOne($this->tbSession.' se');
 		if( ! $tA){
 			return array();
 		}
 		
 		return $tA;
 	} 
 	
 	/**
 	 * 获取用户信息通过账号和密码
 	 * 
 	 * @param	string	$account	账号
 	 * @param	string	$password	密码
 	 * @return	array
 	 */
 	public function getUserInfoByAccountAndPassword($account, $password){
 	
 		if( ! $account || ! $password){
 			return array();
 		}
 		$this->db->select('u.name,u.status,u.id')
 				 ->where(array('u.account' => $account, 
 				 			   'password' => $password,
 				 ));	
 		$tA = $this->getOne($this->tbUser.' u');
 		if( ! $tA){
 			return array();
 		}
 		
 		return $tA;
 	}
 	
 	/**
 	 * 添加登录sessionid
 	 * 
 	 * @param	integer $userId		用户id
 	 * @param	string	$sessionid	会话id
 	 * @return	boolean
 	 */
 	public function addUserSession($userId, $sessionid){
 		
 		if( ! $userId || ! $sessionid){
 			return false;
 		}	
 		
 		$data = array(
 					'user_id' => $userId,
 					'sessionid' => $sessionid,
 					'ip' => getClientIp(),
 					'updatetime' => time(),
 					'addtime' => time()
 				);
 		
 		$query = $this->insert($this->tbSession, $data);
 		if( ! $query){
 			
 			$this->db->where(array('user_id' => $userId, 'addtime <=' => time() - 24 * 3600 * 2));
 			
 			return false;
 		}
 		
 		return true;
 	}

    /**
     * 删除管理员
     *
     * @param string $id
     */
    public function deleteUser($id){

        if( ! $id) return false;
        $this->db->where('id', $id);
        return $this->delete($this->tbUser);
    }

 	/**
 	 * 删除登录会话
 	 * 
 	 * @param string $sessionId
 	 */
 	public function deleteSessionId($sessionId){
 		
 		if( ! $sessionId) return false;
 		$this->db->where('sessionid', $sessionId);
 		return $this->delete($this->tbSession);
 	}

    /**
     * 获取管理员列表数据
     * 
     * @param	integer	$type	1：大后台管理员    2：门店管理员
     * @return 	array
     */
    public function getList()
    {
        $send_date_from = get('send_date_from');
        $role = get('role');
        $send_date_to = get('send_date_to');
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if (strlen($send_date_from) && strlen($send_date_to)){
            $this->db->where(array('addtime >= ' => strtotime($send_date_from), 'addtime <= ' => strtotime($send_date_to)));
        }

        if($iSortCol_0 == 2){
            $this->db->order_by('u.addtime '.$sSortDir_0); // 开始时间
        }
        if(!is_numeric($role) && $role == 'admin'){
            $this->db->where('type', 1);
            $this->db->where('role_id', 0);
        }
        if(is_numeric($role) && $role > 0){
            $this->db->where('role_id', $role);
        }
        $this->db->select(
        				'u.id,u.name,u.account,u.addtime,u.status,u.type,r.name as role_name'
        			)
//        		 ->where('type', 1)
                ->join($this->tbRole.' r','r.id = u.role_id', 'left')
            	 ->order_by('u.id desc');
        
        $data = $this->pagination($this->tbUser.' u');
        return $data;
 	}

 	/**
 	 * 保存管理员
 	 * @param 	array 	$data
 	 * @param   integer $id
 	 * @return	boolean|integer
 	 */
 	public function save($data, $id = 0){
 		
// 		$data['type'] = 1;
 		
 		if($id){
 			$this->db->where('id', $id);
 			return $this->update($this->tbUser, $data);
 		}
 		
 		return $this->insert($this->tbUser, $data);
 	}

    /**
     * 改变状态 公共方法
     * @param	integer	$id		管理员id
     * @param	integer	$status	状态
     * @return	boolean
     */
    public function changeStatus($id, $status){
    	
        if( ! $id) return false;
        $config = $this->_getStatus();
        if( ! array_key_exists($status, $config)){
        	return false;
        }
        
        $this->db->where(array('id' => $id));
        if($this->update($this->tbUser, array('status' => $status))){
            return true;
        }
        
        return false;
    }
    
    /**
     * 检查账号是否存在
     * @param 	string 	$ccmount	找好
     * @param 	string 	$id  		排除id		
     * @return	boolean
     */
    public function isAccount($ccmount, $id = 0){
    	
    	$this->db->where('account', $ccmount);
    	if($id){
    		$this->db->where(array('id <>' => $id));
    	}
    	
    	if($this->count($this->tbUser)){
    		return true;
    	}
    	
    	return false;
    }
    
    /**
     * 获取管理员详情
     * 
     * @param	integer	$id
     * @return	array
     */
    public function getInfo($id){
    	
    	$this->db->select('id,name,account')
    			 ->where(array('id' => $id));
    	
    	return $this->getOne($this->tbUser);
    }
    
    /**
     * 获取单个管理员信息
     * @param $id       管理员ID
     * @return array    管理员数据
     */
    public function getAdmin($id){
    	$this->db->where(array('id'=>$id));
    	$admin = $this->getOne($this->tbUser);
    	return $admin;
    }

    /**
     * 获取状态显示样式
     * @param 	integer $status
     * @param 	bool    $show
     * @return	string
     */
    protected function _getStatus($status = null, $show = false){

        $config = array(1 => '禁用', 2 => '启用');
        if( ! $status){
            return $config;
        }

        if($status && ! isset($config[$status])){
            return '';
        }

        if( ! $show){
            return $config[$status];
        }


        if($status == 1){
            return '<span class="label label-danger">'.$config[$status].'</span>';
        }else if($status == 2){
            return '<span class="label label-success">'.$config[$status].'</span>';
        }

        return'';
    }

    /**
     * 获取平台支出
     */
    public function getExpenditure($startTime = 0, $endTime = 0){
        get_instance()->loadModel('MerchantBalanceModel', 'mBalance', 'merchant');
        get_instance()->loadModel('ConsumerBuyModel', 'mBuy', 'consumer');
        $balanceLog = $this->mBalance->getTotalBalanceLog($startTime, $endTime);
        $buyLog = $this->mBuy->getTotalBuyLog($startTime, $endTime);

        $withdrawals = isset($balanceLog['withdrawals']) ? ltrim($balanceLog['withdrawals'], '-') : 0;
        $blRefund = isset($buyLog['refund']) ? $buyLog['refund'] : 0;
        $blWithdrawals = isset($buyLog['withdrawals']) ? ltrim($buyLog['withdrawals'], '-') : 0;
        return round($withdrawals+$blRefund+$blWithdrawals, 2);
    }
}